package com.menggudf.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import com.menggudf.entity.MyCaseHistory;

@Repository
public class MyCaseHistoryDao{
    
    private static final Log log = LogFactory.getLog(MyCaseHistoryDao.class);

    @PersistenceContext(unitName = "medicalUnit")
    private EntityManager entityManager;

    public void persist(MyCaseHistory transientInstance) {
        try {
            entityManager.persist(transientInstance);
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void remove(MyCaseHistory persistentInstance) {
        try {
            entityManager.remove(persistentInstance);
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    public MyCaseHistory merge(MyCaseHistory detachedInstance) {
        try {
            MyCaseHistory result = entityManager.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public MyCaseHistory findById(int id) {
        try {
            MyCaseHistory instance = entityManager.find(MyCaseHistory.class, id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List<MyCaseHistory> getMyCaseHistorys(
            String userCode,
            String roleCode,
            int pageSize,
            int offset) {
        try {
            StringBuffer sqld = new StringBuffer("from MyCaseHistory m where m.userCode=?1 and m.roleCode=?2 order by m.createdTime desc");
            Query query = entityManager.createQuery(sqld.toString())
                    .setParameter(1, userCode).setParameter(2, roleCode).setFirstResult(offset).setMaxResults(pageSize);
            return query.getResultList();
        } catch (Exception e) {
            log.error("getMyCaseHistorys fail",e);
            throw e;
        }
    }

    public long getMyCaseHistorysCount(String userCode, String roleCode) {
        try {
            StringBuffer sqld = new StringBuffer("select count(*) from MyCaseHistory m where m.userCode=?1 and m.roleCode=?2 ");
            Query query = entityManager.createQuery(sqld.toString())
                    .setParameter(1, userCode).setParameter(2, roleCode);
            return (long) query.getSingleResult();
        } catch (Exception e) {
            log.error("getMyCaseHistorysCount fail",e);
            throw e;
        }
    }

}
